package com.future.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.future.allUtils.utils.JwtUtil;
import com.future.allUtils.utils.TokenRefreshUtil;
import com.future.domain.LoginUserDetails;
import com.future.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

import static com.future.allUtils.constants.RedisCacheConstants.*;

/**
 * 登录认证过滤器
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TokenRefreshUtil tokenRefreshUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");

        //token判空
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request, response);
            return;
        }

        // 2. 解析Token并校验有效性
        String userIdStr = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userIdStr = claims.getSubject();
            if (!StringUtils.hasText(userIdStr)) {
                throw new IllegalArgumentException("Token中用户ID为空");
            }
        } catch (Exception e) {
            // Token解析失败，直接放行
            filterChain.doFilter(request, response);
            return;
        }


        // 3. 验证Redis中是否存在该token
        long userId = Long.parseLong(userIdStr);
        String redisTokenKey = LOGIN_TOKEN_PREFIX + userId;
        String redisToken = stringRedisTemplate.opsForValue().get(redisTokenKey);

        // 检查Redis中的token是否存在且与请求中的token一致
        if (!StringUtils.hasText(redisToken) || !redisToken.equals(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 4. 检查并刷新token
        String newToken = tokenRefreshUtil.checkAndRefreshToken(userId, token);
        if (newToken != null) {
            // 将新token放入响应头
            response.setHeader("Authorization", newToken);
            // 添加一个自定义头标识token已刷新
            response.setHeader("Token-Refreshed", "true");
        }

        // 5. 从redis中获取权限信息封装到Authentication中
        String redisKey = USER_INFO_PREFIX + userId;
        String loginUserJson = stringRedisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.hasText(loginUserJson)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 反序列化
        LoginUserDetails loginUser = objectMapper.readValue(loginUserJson, LoginUserDetails.class);

        // 处理权限信息（避免空指针）
        if (loginUser.getPermissions() == null) {
            loginUser.setPermissions(Collections.emptyList());
        }

        // 存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 放行
        filterChain.doFilter(request, response);
    }
}
